using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;

namespace ExtensionHelper.Util
{
    /// <summary> 
    /// 载入资源中的动态链接库(dll)文件
    /// </summary>
    public static class LoadResourceDll
    {
        //用法
        //1、类中的方法只能在程序中Program中运行
        //2、将需要加载的Dll放在main.exe中的资源Resource中即可


        private static string mExeName;
        /// <summary> 在对程序集解释失败时触发
        /// </summary>
        /// <param name="sender">AppDomain</param>
        /// <param name="args">事件参数</param>
        private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
            dllName = dllName.Replace(".", "_");
            if (dllName.EndsWith("_resources")) return null;
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager(mExeName + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
            byte[] bytes = (byte[])rm.GetObject(dllName);
            return System.Reflection.Assembly.Load(bytes);
        }

        /// <summary> 
        /// 注册资源中的dll(合并dll到主Exe文件中)
        /// </summary>
        /// <param name="pattern">*表示连续的未知字符,_表示单个未知字符,如*.dll</param>
        private static void RegistDLL(string exeName = "")
        {
            mExeName = exeName;
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
        }
    }
}
